package org.shiki.hrm.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import org.shiki.hrm.domain.LoginUser;
import org.shiki.hrm.domain.UserMeal;
import org.shiki.hrm.dto.LoginDto;
import org.shiki.hrm.dto.RTokenDto;
import org.shiki.hrm.mapper.LoginUserMapper;
import org.shiki.hrm.mapper.UserMealMapper;
import org.shiki.hrm.service.ILoginUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.shiki.hrm.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author shiki
 * @since 2022-03-09
 */
@Service
public class LoginUserServiceImpl extends ServiceImpl<LoginUserMapper, LoginUser> implements ILoginUserService {

	@Autowired
	private LoginUserMapper loginUserMapper;

	@Autowired
	private UserMealMapper userMealMapper;

	@Override
	public Long entrying(LoginUser loginUser) {
		//保存t_login_user  返回的主键会直接封装到当前的loginuser对象中
		loginUserMapper.insert(loginUser);
		//保存t_user_meal
		UserMeal meal = new UserMeal();
		meal.setMealId(loginUser.getMealId());
		Long loginId = loginUser.getId();
		meal.setLoginId(loginId);
		userMealMapper.insert(meal);
		return loginId;
	}

	/**
	 * 登录
	 * @param loginDto
	 * @return
	 */
	@Override
	public AjaxResult login(LoginDto loginDto) {
		// 参数校验
		Assert.notNull(loginDto.getUsername(), "用户名不能为空!");
		Assert.notNull(loginDto.getPassword(), "密码不能为空!");
		// 根据用户类型选择对应客户端id
		Integer type = loginDto.getType();
		String clientId;
		String secert;
		if (type == 1){
			clientId = "admin";
			secert = "1";
		} else {
			clientId = "website";
			secert = "1";
		}
		// 准备url,发起HTTP请求获取token
		String url = "http://localhost:3010/oauth/token?client_id=%s&client_secret=%s&grant_type=password&redirect_uri=http://www.baidu.com&username=%s&password=%s";
		url = String.format(url, clientId, secert, loginDto.getUsername(), loginDto.getPassword());
		String s = HttpUtil.get(url);
		System.out.println(s);
		Map map = JSON.parseObject(s, Map.class);
		return AjaxResult.me().setResultObj(map);
	}

	@Override
	public AjaxResult rtoken(RTokenDto rTokenDto) {
		// 参数校验
		Assert.notNull(rTokenDto.getRtoken(), "刷新token不能为空!");
		// 根据用户类型选择对应客户端id
		Integer type = rTokenDto.getType();
		String clientId;
		String secert;
		if (type == 1){
			clientId = "admin";
			secert = "1";
		} else {
			clientId = "website";
			secert = "1";
		}
		// 准备url,发起HTTP请求获取token
		String url = "http://localhost:3010/oauth/token?grant_type=refresh_token&refresh_token=%s&client_id=%s&client_secret=%s";
		url = String.format(url, rTokenDto.getRtoken(), clientId, secert);
		String s = HttpUtil.get(url);
		System.out.println(s);
		Map map = JSON.parseObject(s, Map.class);
		return AjaxResult.me().setResultObj(map);
	}
}
